package com.zhupf.part7;

/**
 * @author zhupf
 * @date 2023年11月17日 16:03
 * @Description
 *
 * 19. 删除链表的倒数第 N 个结点
 */
public class RemoveNthFromEnd {

    public static void main(String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
//        ListNode head = new ListNode(1);
        removeNthFromEnd(head, 5);
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode l1 = head;
        ListNode l2 = head;
        ListNode pre = null;
        while (l1 != null) {
            if (n < 1) {
                pre = l2;
                l2 = l2.next;
            }
            l1 = l1.next;
            n--;
        }
        if (pre == null) {
            head = head.next;
        } else {
            pre.next = l2.next;
        }
        return head;

    }

    public static ListNode removeNthFromEnd2(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode first = head;
        ListNode second = dummy;
        for (int i = 0; i < n; i++) {
            first = first.next;
        }
        while (first != null) {
            second = second.next;
            first = first.next;
        }
        second.next = second.next.next ;
        return dummy.next;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}
